<?php

namespace yunj\app\admin\middleware;

use think\facade\Route;
use think\Response;
use think\response\Json;
use think\tests\DispatchTest;
use yunj\app\admin\enum\EnableLoginAuth;
use yunj\app\admin\enum\RedisKey;
use yunj\app\admin\enum\State;
use yunj\app\admin\model\AdminMember;
use yunj\app\admin\model\AdminMemberRole;
use yunj\app\admin\service\member\log\LogRecordService;
use yunj\app\admin\service\auth\AuthService;
use yunj\app\admin\service\route\RouteFileService;
use yunj\app\admin\service\route\RouteRequestService;
use yunj\core\enum\TipsTemplet;

final class Init extends Middleware {

    public function handle($request, \Closure $next) {
//        RouteFileService::reset();
//        dd('系统升级中...敬请期待...');
//        return $next($request);
        // 1. 获取当前请求对应的路由请求项数据
        request()->adminRouteRequestData = RouteRequestService::getValidRouteRequestData(
            request()->baseUrl(),
            request_method(),
            request()->all()
        );
//        if (strstr(request()->baseUrl(), 'login')) {
//            dump(request()->baseUrl());
//            dd(request()->adminRouteRequestData);
//        }
        // 2. 处理登录鉴权
        $this->handleLoginAuth();
        // 3. 处理成员日志
        admin_member_log();
        $response = $next($request);
        // 4. 处理成员日志记录响应json
        $this->handleMemberLogRecordResponseJson($response);

        return $response;
    }

    // 处理登录鉴权
    private function handleLoginAuth(): void {
        $member = admin_member_login_service()->validate();
        if ($member) {
            request()->member = $member;
        }
        // 登录校验
        $adminRequestDbData = request()->adminRouteRequestData;
        if (!$adminRequestDbData || $adminRequestDbData['final_enable_login_auth'] !== EnableLoginAuth::ON) {
            return;
        }
        if (!$member) {
            request()->isAjax() ? throw_json(10002) : throw_redirect(tips_url(TipsTemplet::OVERDUE()));
        }
        // 权限校验
        if (admin_member_auth_check()) {
            return;
        }
        request()->isAjax() ? throw_json(10002) : throw_redirect(tips_url(TipsTemplet::NO_AUTH()));
    }

    // 处理成员日志记录响应json
    private function handleMemberLogRecordResponseJson($response) {
        try {
            if ($response instanceof Json) {
                $content = $response->getContent();
                // json内容小于5000字符，则记录日志
                if (mb_strlen($content, 'utf-8') < 5000) {
                    admin_member_log(['response_content' => $content]);
                }
            }
        } catch (\Throwable $e) {
            log_exception($e,'','admin log recoed response fail!');
        }
    }

}